package playn.game.core;

import java.util.HashMap;

import playn.core.Image;
import playn.core.PlayN;
import playn.game.backgrounds.Background;
import playn.game.level.Level;
import playn.game.menu.Menu;

import static playn.core.PlayN.*;

import tiled.simple.core.Map;

public class Game implements playn.core.Game {
	
	public static int SCREEN_WIDTH=640;
	public static int SCREEN_HEIGHT=480;
	public static boolean initialized=false;
	public static final float PIXEL_PER_METER=500;

	public static HashMap<String, Image> images;
	public static HashMap<String,Map> maps;
	
	public static SoundManager soundManager;

	public Controls controls;

	public static int lastOpenedLevel=1;
	public static final String LAST_OPENED_LEVEL_NUMBER_ID="LOLN";
	
	
	@SuppressWarnings("static-access")
	public Game(Controls controls,HashMap<String,Map> maps,HashMap<String, Image> images) {
		this.maps=maps;
		this.images=images;
		this.controls=controls;
	}

	public static Map currentMap;
	
	public static Background background;
	public static Menu menu;
	public static Level level;
	
	public static boolean action=false;
	
	public void init() {
		persistence_load();
		

		
		graphics().rootLayer().setScale(1,1);
		
		keyboard().setListener(controls);

		soundManager=new SoundManager();

		background=new Background();
	    graphics().rootLayer().add(background.layer);
   
	    level=new Level();
	    graphics().rootLayer().add(level.layer);
	    
	    menu=new Menu();
	    graphics().rootLayer().add(menu.layer);

	    graphics().rootLayer().add(soundManager.layer);

		menu.currentState=Menu.START;
		menu.currentState.start();
		menu.currentState.show();
	}

	
	public void update(float delta) {
		if(action){
			level.update(delta);
		}
		
		menu.update(delta);
	}

	public void paint(float alpha) {
	}

	public int updateRate() {
		return 15;
	}
	
	private void persistence_load(){
		String loln=PlayN.storage().getItem(LAST_OPENED_LEVEL_NUMBER_ID);
		System.out.println("persistence load {"+LAST_OPENED_LEVEL_NUMBER_ID+"="+loln+"}");
		
		if(loln!=null){
			if(Integer.parseInt(loln)>1){
				lastOpenedLevel=Integer.parseInt(loln);
			}
		}
	}
	
	public void persistence_save(){
		String loln=String.valueOf(lastOpenedLevel);
		PlayN.storage().setItem(LAST_OPENED_LEVEL_NUMBER_ID,loln);
		System.out.println("persistence save {"+LAST_OPENED_LEVEL_NUMBER_ID+"="+loln+"}");
	}
}
